// CDN_APP_SculleryServer.h
//
// Copyright (c) 2011 LRUnit, LLC All Rights Reserved.
// Author : Kim McKinley
//
// This product includes software developed by :
//  LRUnit, LLC
//
// This software is under the terms of the MIT License :
/*
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*/

#if !defined(CDN_APP_SculleryServer_h)
#define CDN_APP_SculleryServer_h


/* **********************************************************************
All the includes for Scullery Server.
Keep all of them in one place so not to get stuck in 'include' hell
*/

// OS related
#include <sys/stat.h>
#include <conio.h>
#include <direct.h>
#include <process.h>
#include <time.h>

// STL library
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <string>
#include <map>
#include <sstream>
#include <fstream>
#include <vector>
#include <stack>

// Portability - or at least an attempt
#include "OS_Specific.h"
// SQLite library
#include "sqlite/sqlite3.h"
// XML
#include "XMLW_xmlwriter.h"

// **********************************************************************
// Globals
/// All can see the values read from the configuration file
//   Decided against the overhead of a mutex, thus you'll need to bounce server to
//    safely modify configuration parameters
typedef std::map< std::string, std::string > options;
std::map< std::string, options > gConfig;

/// SQLite Shell entry point - allowing console access to the SQLite Command Shell
//   See http://www.sqlite.org/sqlite.html as the authority on using the shell.
//  The only change to the SQLite source is the name of the 'main' shell function
//   has been changed to 'sqlitemain'.
extern "C" { int sqlitemain(int argc, char **argv); }
// **********************************************************************

// Server application classes 
#include "CDN_DB_Sqlite.h"          // SQLite database access
#include "CDN_WEB_MSG_Http.h"       // HTTP 1.1 message storage
#include "CDN_WEB_SRV_Extensions.h" // Server extensions that build replies
#include "CDN_WEB_SRV_Handler.h"    // The request, server extension, and reply handler
#include "CDN_NET_TCP_Acceptor.h"   // TCP/IP network interface
#include "CDN_APP_Configuration.h"  // Application configuration settings

namespace cdn {
  namespace app {

// **********************************************************************

/// Server Application
class SculleryServer
{
public:

/// Say hi!
void Welcome()
{
  std::cout <<
    "Welcome to Scullery Server!" << std::endl << std::endl;
}

/// Show command line usage help
void Usage()
{
  std::cout <<
    "Usage:" << std::endl << 
    " 'SculleryServer.exe' will use the configuration file named '" << DEFAULT_CONFIG_FILE << "'." << std::endl <<
    "   " << DEFAULT_CONFIG_FILE << " resides in the same directory as the server application." << std::endl <<
    " or can specify a configuration file in the command line " << std::endl <<
    " 'SculleryServer.exe SomeFilePath'" << std::endl << std::endl;
}

/// Display the server command menu
void DisplayMenu()
{
    std::cout << std::endl << "Server Menu: " << std::endl << 
    std::left << 
    std::setw(24) << " .doc" << "Bring up Scullery documentation in web brower" << std::endl <<
    std::setw(24) << " .bye" << "Shutdown" << std::endl <<
    std::setw(24) << " .edit" << "Edit the current configuration file" << std::endl <<
    std::setw(24) << " .config" << "Display the current configuration" << std::endl <<
    std::setw(24) << " .sqlite" << "Start Sqlite Shell with a :memory: database" << std::endl << 
    std::setw(24) << " .sqlite dbname" << "Start Sqlite Shell using database dbname" << std::endl << 
    std::setw(24) << " .sqlite dbname sqlcmd" << "Sqlite Shell executes SQL command" << std::endl << 
    std::setw(24) << " .hide" << "Hide the console window - DON'T FORGET :" << std::endl <<
    std::setw(24) << " " << "  http://localhost:" << gConfig["DEFAULT"]["SERVER_PORT"] << 
                          "/ShowConsole to show it again!"  << std::endl;
}

/// Display the current [Default] section configuration on the console
void DisplayConfiguration()
{
  std::map< std::string, options >::iterator s;
  options::iterator c;

  std::cout << std::endl << "Current configuration from " <<
    gConfig["CONFIG"]["FILENAME"] <<  " : " << std::endl << std::endl;

  for ( s = gConfig.begin(); s != gConfig.end(); ++s )
  {
    // Only going to show the DEFAULT section - the MIME section can be silly long
    if ( s->first != "DEFAULT" ) continue;
    std::cout << "[" << s->first << "]" << std::endl;

    // Display the option and value
    for (c = s->second.begin(); c != s->second.end(); ++c )
      std::cout << "   " << c->first << " = " << c->second << std::endl;
    std::cout << std::endl;

    // All done with DEFAULT section so don't need the rest
    break;
  }
}

/// Process console user commands
void CommandHandler(bool prompt = true)
{
  std::string cmd;

  while ( true )
  {
    // Prompt the user
    if ( prompt ) std::cout << gConfig["DEFAULT"]["PROMPT"];

    // If only the Enter key is pressed display the server menu
    std::getline(std::cin, cmd);
    if ( !cmd[0] ) { DisplayMenu(); continue; }

    // Got a command - so process it

    // Enter the SQLite shell?
    if ( cmd.substr(0,7) == ".sqlite")
    {
      char *sqlcommandline[] = { "sqlite3", "XMLStats.sqlite" };
      sqlitemain(1, sqlcommandline);
      continue;
    }
    // Display the scullery documentation in a web browser?
    else if ( cmd.substr(0,5) == ".doc" )
    {
      std::stringstream document;
      document << "start http://localhost:" << gConfig["DEFAULT"]["SERVER_PORT"] << "/scullery/index.html";
      system(document.str().c_str());
      continue;
    }
    // Edit the configuration file?
    else if ( cmd.substr(0,7) == ".edit" )
    {
      std::stringstream document;
      document << "start " << gConfig["CONFIG"]["FILENAME"];
      system(document.str().c_str());
      continue;
    }
    // Display the configuration file?
    else if ( cmd.substr(0,7) == ".config" )
    {
      DisplayConfiguration();
      continue;
    }
    // Hide the console window?
    else if ( cmd.substr(0,5) == ".hide" )
    {
      ShowWindow( GetConsoleWindow(), SW_HIDE );
      continue;
    }
    // Where is the love? User don't want us around any more
    else if ( cmd.substr(0,4) == ".bye" )
    {
      return;
    }
    // No idea what the user wants to do :(
    else
    {
      std::cout << "Unknown command '" << cmd << "'" << std::endl;
    }
  }

}

/// Create a directory to hold the SQLite databases
void CreateDirectory(const std::string &dirname)
{
  if ( _mkdir(dirname.c_str()) == -1 )
  {
    // Ignore error if directory already exists
    if ( errno != 17 )
    {
      char buf[256];
      std::cout << "Error creating '" << dirname <<
        "' directory : (" << errno << ") " << strerror_s(buf,256,errno) << std::endl << 
      "Continuing anyway..." << std::endl << std::endl;
      return;
    }
  }

  // Inform user of the default parent directories for web and database files
  if ( dirname == gConfig["DEFAULT"]["DATABASE_DIRECTORY"] )
    std::cout << "Default sub-directory for SQLite databases is '" << dirname << "'." << std::endl;
  else if ( dirname == gConfig["DEFAULT"]["WEB_DIRECTORY"] )
    std::cout << "Default sub-directory for Web sites is '"  << dirname << "'." << std::endl << std::endl;
}

}; // class SculleryServer

} // namespace app
} // namespace cdn

#endif

